<?php
namespace app\api\controller;

use app\common\controller\BaseController;
use app\common\model\Device;

class DeviceController extends BaseController
{
    /**
     * Register device info
     * @return \think\response\Json
     */
    public function register()
    {
        $data = input('post.');
        
        // Validate required fields
        if (empty($data['platform']) || empty($data['device_info'])) {
            return json(['code' => 400, 'msg' => 'Invalid parameters']);
        }

        // Save device info
        $device = Device::create([
            'platform' => $data['platform'],
            'device_info' => json_encode($data['device_info']),
            'create_time' => time()
        ]);

        return json([
            'code' => 200,
            'data' => [
                'device_id' => $device->id
            ]
        ]);
    }

    /**
     * Match devices between platforms
     * @return \think\response\Json 
     */
    public function match()
    {
        $data = input('post.');
        
        // Validate required fields
        if (empty($data['h5_device_info']) || empty($data['app_device_info'])) {
            return json(['code' => 400, 'msg' => 'Invalid parameters']);
        }

        // Extract matching criteria
        $h5Info = $data['h5_device_info'];
        $appInfo = $data['app_device_info'];

        // Matching logic
        $matchResult = $this->matchDevices($h5Info, $appInfo);

        return json([
            'code' => 200,
            'data' => [
                'is_match' => $matchResult,
                'match_score' => $this->calculateMatchScore($h5Info, $appInfo)
            ]
        ]);
    }

    /**
     * Match devices based on available info
     */
    private function matchDevices($h5Info, $appInfo)
    {
        // 1. Check device ID match
        if (!empty($h5Info['deviceId']) && !empty($appInfo['deviceId'])) {
            return $h5Info['deviceId'] === $appInfo['deviceId'];
        }

        // 2. Check MAC address match
        if (!empty($h5Info['macAddress']) && !empty($appInfo['macAddress'])) {
            return $h5Info['macAddress'] === $appInfo['macAddress'];
        }

        // 3. Check fingerprint match
        if (!empty($h5Info['deviceFingerprint']) && !empty($appInfo['deviceFingerprint'])) {
            return $h5Info['deviceFingerprint'] === $appInfo['deviceFingerprint'];
        }

        // 4. Check other criteria
        return $this->calculateMatchScore($h5Info, $appInfo) > 0.8;
    }

    /**
     * Calculate match score based on multiple factors
     */
    private function calculateMatchScore($h5Info, $appInfo)
    {
        $score = 0;
        
        // Compare screen resolution
        if ($h5Info['screenWidth'] === $appInfo['screenWidth'] &&
            $h5Info['screenHeight'] === $appInfo['screenHeight']) {
            $score += 0.2;
        }

        // Compare platform
        if ($h5Info['platform'] === $appInfo['platform']) {
            $score += 0.1;
        }

        // Compare user agent
        if (strpos($h5Info['userAgent'], $appInfo['userAgent']) !== false) {
            $score += 0.2;
        }

        // Compare network info
        if ($h5Info['networkType'] === $appInfo['networkType']) {
            $score += 0.1;
        }

        // Compare language
        if ($h5Info['language'] === $appInfo['language']) {
            $score += 0.1;
        }

        // Compare timezone
        if ($h5Info['timezone'] === $appInfo['timezone']) {
            $score += 0.1;
        }

        // Compare hardware info
        if ($h5Info['cpuCores'] === $appInfo['cpuCores'] &&
            $h5Info['memory'] === $appInfo['memory']) {
            $score += 0.2;
        }

        return $score;
    }
}
